<?php

require_once("../models/authorization.php");
require_once("../models/DatabaseUtils.php");
require_once("../models/post.php");
require_once ('../includes/smarty/libs/Smarty.class.php');
  
class AdminCPRenderer{
	
	private $smarty;
	private $session;
	
	public function AdminCPRenderer(){
		
		$this->smarty = new Smarty();
		$this->session = new Authorization();
				
		if(isset($_POST['username']) && isset($_POST['password'])){
  	
			$username = $_POST['username'];
  			$password = $_POST['password'];

	  		if (!$this->session->login($username, $password))
    			header('Location: error.php?error=credentials');
	  	}

		if(!$this->session->checkLogin()){
			$this->renderLoginPage();
			return;
		}
		
		if($_REQUEST['do'] == "createDB")
			DatabaseUtils::createDatabase();

		$this->getAdminCPPlaceholderValues();
		$this->renderAdminCP();
	}
	
	const USERNAME_PLACEHOLDER_NAME = "username";

	const DATABASE_ERROR_PLACEHOLDER_NAME = "databaseError";
	
	const DATABASE_NAME_PLACEHOLDER_NAME = "dbname";

	const NUMBER_OF_POSTS_PLACEHOLDER_NAME = "numberOfPosts";

	const NUMBER_OF_CATEGORIES_PLACEHOLDER_NAME = "numberOfCategories";

	private function getAdminCPPlaceholderValues(){
		
		$this->smarty->assign(self::USERNAME_PLACEHOLDER_NAME, $this->session->getUsername());
		$this->smarty->assign(self::DATABASE_ERROR_PLACEHOLDER_NAME, (!DatabaseUtils::databaseExists()));
		$this->smarty->assign(self::DATABASE_NAME_PLACEHOLDER_NAME, DBNAME);
		$this->smarty->assign(self::NUMBER_OF_POSTS_PLACEHOLDER_NAME, Post::getNumberOfPosts());
		$this->smarty->assign(self::NUMBER_OF_CATEGORIES_PLACEHOLDER_NAME, Category::getNumberOfCategories());
	}

	const LOGIN_PAGE_TEMPLATE_NAME = "login.tpl";
	
	private function renderLoginPage(){
		$this->smarty->display(self::LOGIN_PAGE_TEMPLATE_NAME);
	}
	
	const ADMINCP_TEMPLATE_NAME = "admincp.tpl";
	
	private function renderAdminCP(){
		$this->smarty->display(self::ADMINCP_TEMPLATE_NAME);
	}
}  

$adminCP = new AdminCPRenderer();
?>